<template>
  <div class="previewImgVidoeFile">
    <el-dialog
      :visible.sync="show"
      @closed="handelclose"
      center
      lock-scroll
      :append-to-body="true"
      custom-class="showFileDialog"
    >
      <div class="dialogBodyBox" v-loading="loading" v-if="show">
        <div
          class="contentBox"
          v-if="
            [
              'jpg',
              'jpeg',
              'png',
              'gif',
              'bmp',
              'JPG',
              'JPEG',
              'PNG',
              'GIF',
              'BMP',
            ].indexOf(objData.type) !== -1
          "
        >
        <!-- <img :src="objData.fileUrl" ref="img" /> -->
          <el-image 
            lazy
            :src="objData.fileUrl" 
            :preview-src-list="[objData.fileUrl]"
            v-on="$linsteners"
            @close="handelclose"
            ref="preview">
          </el-image>
        </div>
        <div
          class="contentBox playVideoBox"
          v-if="['mp4', 'MP4'].indexOf(objData.type) !== -1"
        >
          <video :src="objData.fileUrl" controls="controls" ref="video1" />
        </div>
        <div
          class="contentBox playVideoBox"
          v-if="['m3u8', 'M3U8'].indexOf(objData.type) !== -1"
        >
          <video
            ref="video2"
            id="video"
            :src="objData.fileUrl"
            autoplay="true"
            controls="true"
            ishowprocessview="true"
            x5-playsinline=""
            playsinline=""
            webkit-playsinline=""
            x5-video-player-type="h5"
            x5-video-player-fullscreen="false"
            direction="0"
            show-play-btn="true"
            object-fit="cover"
          ></video>
        </div>
        <div
          v-if="['docx', 'xlsx', 'pptx','DOCX','XLSX','PPTX'].indexOf(objData.type) !== -1"
          class="contentBox microsoftFile"
        >
          <iframe
            :src="`https://view.officeapps.live.com/op/view.aspx?src=${objData.fileUrl}`"
            width="100%"
            height="100%"
            frameborder="0"
            ref="microsoftIframe"
          ></iframe>
        </div>
        <div
          class="contentBox audioBox"
          v-if="['wav', 'mp3','WAV','MP3'].indexOf(objData.type) !== -1 && show"
        >
          <video
            :src="objData.fileUrl"
            controls="controls"
            class="audioPlayer"
            ref="audio"
          ></video>
        </div>
        <div v-if="objData.type == 'bilibiliPlay'">
          <!-- <iframe
            :src="`https://player.bilibili.com/player.html?bvid=${objData.fileUrl}&page=1&as_wide=1&high_quality=1&danmaku=0`"
            scrolling="no"
            border="0"
            frameborder="no"
            framespacing="0"
            allowfullscreen="true"
            sandbox="allow-top-navigation allow-same-origin allow-forms allow-scripts"
            width="100%"
            height="700px"
          >
          </iframe> -->
          <iframe
            :src="objData.fileUrl"
            width="100%"
            height="700px"
            frameborder="0"
            ref="bilibiliIframe"
          ></iframe>
        </div>
        <div v-if="['pdf','PDF'].indexOf(objData.type) !== -1">
          <embed
            :src="objData.fileUrl"
            type="application/pdf"
            style="width: 90vw; height: 84vh"
            ref="pdf"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Hls from "hls.js";
export default {
  data() {
    return {
      show: false,
      objData: {},
      video: null,
      loading: false, // 进入时的加载
    };
  },
  props: {
    showPerview: Boolean,
    showData: Object,
    fileList: Array,
  },
  watch: {
    showPerview(n, o) {
      this.show = n;
    },
    showData(n, o) {
      // n.fileUrl = n.fileUrl.split("&")[0];
      this.objData = n;
    },
    objData() {
      this.loading = true;
      if (this.objData.type === "m3u8") {
        this.setUrlToVideo();
      }
      this.$nextTick(() => {
        this.checkDOMisLoaded();
      });
    },
  },
  computed: {
    // 过滤文件列表中的图片，用于预览
    filterFileList() {
      return this.fileList?.filter((item) => {
        return (
          [
            "jpg",
            "jpeg",
            "png",
            "gif",
            "bmp",
            "JPG",
            "JPEG",
            "PNG",
            "GIF",
            "BMP",
          ].indexOf(item.type) !== -1
        );
      })?.map((item) => {
        return item.fileUrl;
      }) || [];
    },
  },
  created() {
    if (this.objData.fileUrl) {
      this.setUrlToVideo();
    }
  },
  methods: {
    // 关闭浏览窗口
    handelclose() {
      this.$emit("close");
    },
    // Hls 加载m3u8资源
    videoInit(url) {
      let video = document.getElementById("video");
      if (video.attributes["isLoad"]) return;
      var hls = "";
      hls = new Hls();
      hls.loadSource(url);
      hls.attachMedia(video);
      video.setAttribute("isLoad", true);
    },
    // 设置Video的Url
    setUrlToVideo() {
      let url = this.objData.fileUrl;
      if (url.length > 0) {
        if (this.isUrl(url)) {
          this.$nextTick(() => {
            this.videoInit(url);
          });
        } else {
          alert("URL不合法");
        }
      }
    },
    //判断是否为URL
    isUrl(str) {
      let v = new RegExp(
        "^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$",
        "i"
      );
      return v.test(str);
    },
    // 监听视频加载情况
    listenVideOnload() {
      this.$nextTick(() => {
        this.video = document.getElementById("video");
        if (this.video) {
          this.video.oncanplay = function () {
            this.video.play();
          };
        }
      });
    },
    // 监听当前浏览对象是否已加载完毕
    checkDOMisLoaded() {
      let el = null;
      if (
        [
          "jpg",
          "jpeg",
          "png",
          "gif",
          "bmp",
          "JPG",
          "JPEG",
          "PNG",
          "GIF",
          "BMP",
        ].indexOf(this.objData.type) !== -1
      ) {
        el = this.$refs.img;
        this.loading = false;
      } else if (this.objData.type == "mp4") {
        el = this.$refs.video1;
      } else if (this.objData.type == "m3u8") {
        el = this.$refs.video2;
      } else if (["docx", "xlsx", "pptx"].indexOf(this.objData.type) !== -1) {
        el = this.$refs.microsoftIframe;
      } else if (["wav", "mp3"].indexOf(this.objData.type) !== -1) {
        el = this.$refs.audio;
      } else if (this.objData.type == "bilibiliPlay") {
        el = this.$refs.bilibiliIframe;
      } else if (this.objData.type == "pdf") {
        el = this.$refs.pdf;
      }
      if (el) this.listenOnloaded(el, this.objData.type);
    },
    // 监听元素加载完成
    listenOnloaded(el, type) {
      if (["bilibiliPlay", "docx", "xlsx", "pptx"].indexOf(type) !== -1) {
        el.onload = () => {
          this.loading = false;
        };
      } else if (["m3u8", "mp4", "audio", "wav"].indexOf(type) !== -1) {
        el.oncanplay = () => {
          this.loading = false;
        };
      } else {
        el.addEventListener("load", () => {
          this.loading = false;
        });
      }
    },
  },
  mounted() {
    if (this.objData.type == "m3u8") this.listenVideOnload();
  },
};
</script>

<style lang="stylus">
.el-dialog__wrapper {
  .showFileDialog {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 50px;
    width: min-content;
    min-width: 120px;
    min-height: 100px;
    background: transparent;
    box-shadow: none;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: 0 !important;
    transform: translate(-50%, -50%);

    .el-dialog__header {
      padding: 0;

      .el-dialog__headerbtn {
        z-index: 9;
        top: 12px;
        right: 12px;

        .el-icon-close {
          transition: opacity 0s linear;
          opacity: 0;
        }

        .el-icon-close:before {
          font-size: 22px;
          font-weight: bold;
          color: #d12929;
        }
      }
    }

    .el-dialog__body {
      // width: 100%;
      padding: 0;

      .contentBox {
        width: 100%;
      }

      img {
        max-width: 90vw;
        max-height: 90vh;
        width: auto;
        height: auto;
      }

      .autdioBox {
        .audioPlayer {
          height: 62px;
          min-width: 300px;
        }
      }

      .playVideoBox {
        video {
          outline: none;
          max-width: 60vw;
        }
      }

      .microsoftFile {
        width: 90vw;
        height: 84vh;
      }

      .showImg {
        image-rendering: -webkit-optimize-contrast;
        min-width: 10px;
        // width: 100% !important;
        max-width: 100%;
      }

      .audio {
        background-color: rgba(126, 126, 126, 0.61);
        border-radius: 5px;
      }
    }
  }
}

.el-dialog__wrapper {
  .el-dialog:hover {
    .el-icon-close {
      opacity: 1 !important;
    }
  }
}
</style>